﻿var currentIndex = 0; // 全局变量，用于跟踪当前的同学姓名索引

function addStudent() {
    var table = document.getElementById("studentTable");
    var newRow = table.insertRow(-1);
    var newName = "同学" + (currentIndex + 1); // 根据索引确定新同学的姓名
    currentIndex++; // 更新索引
    var age = Math.floor(Math.random() * 5) + 18; // 年龄在18-22之间随机
    var gender = Math.random() < 0.5 ? "男" : "女"; // 随机性别
    var studentId = Math.floor(Math.random() * 1000); // 随机学号
    var cells = newRow.insertCell(-1);
    cells.innerHTML = newName;
    cells = newRow.insertCell(-1);
    cells.innerHTML = age;
    cells = newRow.insertCell(-1);
    cells.innerHTML = gender;
    cells = newRow.insertCell(-1);
    cells.innerHTML = studentId;
}



function deleteStudent() {
    var table = document.getElementById("studentTable");
    if (table.rows.length > 1) {
        table.deleteRow(-1);
    }
}

function showStatistics() {
    var table = document.getElementById("studentTable");
    var totalStudents = table.rows.length - 1; // 减去表头
    var maleCount = 0;
    var femaleCount = 0;
    for (var i = 1; i < table.rows.length; i++) {
        var gender = table.rows[i].cells[2].innerHTML;
        if (gender === "男") {
            maleCount++;
        } else {
            femaleCount++;
        }
    }
    var malePercentage = (maleCount / totalStudents) * 100;
    var femalePercentage = (femaleCount / totalStudents) * 100;
    alert("学生总数: " + totalStudents + "\n男生比例: " + malePercentage.toFixed(2) + "%\n女生比例: " + femalePercentage.toFixed(2) + "%");
}
